#coding:utf-8
import os
import string
from common.iniconfig import iniconfig

class dict_history:
        def __init__(self,file="history"):
                self.ini=iniconfig("settings")
                if not os.path.exists(file):
                        f=open(file,"w")
                        f.close()
                self.file_name=file
        
        def __del__(self):
                pass
        
        def set_file(self,file):
                self.file_name=file
                
        def set_num(self,val):
                self.ini.set_item("history_num",str(val))
                
        def get_num(self):
                return string.atoi( self.ini.get_item("history_num"))
        
        def get_max(self):
                f=open(self.file_name,"r")
                a=0
                while f.readline()!="":
                        a=a+1
                f.close()
                return a
                        
        def add_history(self,history):
                if history.strip()=="":
                        return
                if history in self.read_history("a"):
                        return
                f=open(self.file_name,"r")
                a=f.read()
                f.close()
                a=history+"\n"+a
                f=open(self.file_name,"w")
                f.write(a)
                f.close()
        
        def del_history(self):
                f=open(self.file_name,"w")
                f.close()
        
        def read_history(self,mode="v"):
                f=open(self.file_name,"r")
                a= f.readlines()
                for m in range(0,len(a)-1):
                        a[m]=a[m].replace("\n","")
                if mode=="a":
                        return a
                if mode=="v":
                        if len(a)>self.get_num():
                                return a[:self.get_num()]
                        else:
                                return a
                        
        